package Utils;


import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * The type Receive object.
 *
 * @author dzr
 * @version 1.0
 */
public class ReceiveObject {
    /**
     * Receive packet and change into specific object.
     *
     * @param socket the socket
     * @return the object
     * @throws IOException the io exception
     */
    public static Object  receiveObject(DatagramSocket socket) throws IOException {
        byte[] container = new byte[2048];
        DatagramPacket packet = new DatagramPacket(container, 0, container.length);
        socket.receive(packet);

        byte[] data = packet.getData();

        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        BufferedInputStream bis = new BufferedInputStream(bais);
        ObjectInputStream ois = new ObjectInputStream(bis);

        Object msg = null;
        try {
            msg = ois.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        ois.close();
        bis.close();
        bais.close();

        return msg;
    }
}
